import random
import string
from datetime import datetime, timedelta, time
from time import sleep
import json
from dao.mqtthelp_v2 import MQTTClient


# 生成每个雷达设备的车辆数据,并确保有一辆车是出去的
def creatData(list, device, num_devices):
    all_vehicle_data = []
    current_time = datetime.now()

    for i in range(num_devices):
        location = list[i]
        device_num = f"{device}{i + 1}"
        # timestamp = current_time.strftime("%Y/%m/%d-%H:%M:%S")
        timestamp_milliseconds = current_time.strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]  # 毫秒级

        num_vehicles = random.randint(2, 6)  # 每个设备随机生成1-5辆车
        objects_list = []

        for j in range(num_vehicles):
            vehicle_data = {
                "ID": j + 1,
                "x": -320,  # x坐标
                "y": 15000,  # y坐标
                "v_x": 0,  # x轴速度
                "v_y": -2120,  # y轴速度
                "length": 480,
                "width": 190,
                "height": 170,
                "type": random.randint(0, 2),  # 随机生成车辆类型
                "class": random.randint(0, 11),  # 随机生成车辆类别   15以后的不识别
                "color": 0,
                "plate_color": random.randint(6, 7),  # 随机生成车牌颜色
                "lane": random.randint(1, 3),  # 随机选择车道
                "lane_dir": 1,  # 车道方向
                "km_dir": 1,
                "event": 0,
                "plate": #"湘A12345",
                "湘" + random.choice(string.ascii_uppercase[:8]) +''.join(random.choices(string.ascii_uppercase + string.digits, k=5)),
                # 生成随机车牌号：湘A-H + 5位数字或大写字母
                "stake_mark": list[i],
                "longitude": 112.123456,
                "latitude": 28.654321,
                "altitude": 45.00,
                "speed": round(random.uniform(0, 100), 2),  # 随机生成速度
                "heading": 49.23  # 随机生成车头方向
            }

            objects_list.append(vehicle_data)

        device_data = {
            "location": location,
            "device_num": device_num,
            "timestamp": timestamp_milliseconds,
            "number": num_vehicles,
            "objects_list": objects_list
        }

        all_vehicle_data.append(device_data)

    #  确保最后一个雷达参数的plate数据和车辆数量为第一个雷达的第一条数据,最后一个雷达时间加2~20分钟
    if all_vehicle_data:
        first_device_data = all_vehicle_data[0]
        last_device_data = all_vehicle_data[-1]
        last_device_data["number"] = 1
        # 取最后一个topic的第一条数据
        last_device_data["objects_list"] = last_device_data["objects_list"][0]
        # 替换最后一个topic的车牌为第一个topic第一条数据的车牌
        last_device_data["objects_list"]["plate"] = first_device_data["objects_list"][0]["plate"]

        # 将最后一个雷达的时间在当前时间的基础上加15分钟
        last_device_data["timestamp"] = (current_time + timedelta(minutes=15)).strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]

    # 输出所有雷达设备的数据
    return all_vehicle_data

# 生成每个雷达设备的车辆数据,更真实的场景数据
def creatRealData(list, device, num_devices):
    all_real_vehicle_data = []
    current_time = datetime.now()

    for i in range(num_devices):
        location = list[i]
        device_num = f"{device}{i + 1}"
        # timestamp = current_time.strftime("%Y/%m/%d-%H:%M:%S")
        timestamp_milliseconds = current_time.strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]  # 毫秒级

        num_vehicles = random.randint(1, 2)  # 每个设备随机生成1-5辆车
        objects_list = []

        for j in range(num_vehicles):
            vehicle_data = {
                "ID": j + 1,
                "x": -320,  # x坐标
                "y": 15000,  # y坐标
                "v_x": 0,  # x轴速度
                "v_y": -2120,  # y轴速度
                "length": 480,
                "width": 190,
                "height": 170,
                "type": random.randint(0, 2),  # 随机生成车辆类型
                "class": random.randint(0, 11),  # 随机生成车辆类别   15以后的不识别
                "color": 0,
                "plate_color": random.randint(6, 7),  # 随机生成车牌颜色
                "lane": random.randint(1, 3),  # 随机选择车道
                "lane_dir": 1,  # 车道方向
                "km_dir": 1,
                "event": 0,
                "plate": #"湘A12345",
                    "湘" + random.choice(string.ascii_uppercase[:8]) +''.join(random.choices(string.ascii_uppercase + string.digits, k=5)),
                # 生成随机车牌号：湘A-H + 5位数字或大写字母
                "stake_mark": list[i],
                "longitude": 112.123456,
                "latitude": 28.654321,
                "altitude": 45.00,
                "speed": round(random.uniform(0, 100), 2),  # 随机生成速度
                "heading": 49.23  # 随机生成车头方向
            }

            objects_list.append(vehicle_data)

        device_data = {
            "location": location,
            "device_num": device_num,
            "timestamp": timestamp_milliseconds,
            "number": num_vehicles,
            "objects_list": objects_list
        }

        all_real_vehicle_data.append(device_data)
    return all_real_vehicle_data

# nanxian_main=["SK2+612", "SK2+732","SK2+852", "SK2+972", "SK3+92", "SK3+212", "SK3+332", "SK3+452", "SK3+572", "SK3+692", "SK3+812", "SK3+932","SK4+52", "SK4+172", "SK4+292", "SK4+412", "SK4+532", "SK4+652", "SK4+772", "SK4+892"]
# nanxian_zhuru =["SK2+132",  "SK2+252", "SK2+372", "SK2+492"]  # 南主入口：SK2+132
# nanxian_zharu =["CK0+170", "CK0+290","CK0+410", "CK0+530"]  # 南闸入口：CK0+170
# nanxianzhuchu=["SK5+12", "SK5+132","SK5+252", "SK5+372", "SK5+372"]  # 南主出口：SK5+372
# nanxianzhachu=[ "EK0+96", "EK0+216"]  # 南闸出口：EK0+216
#
# nanxian2=["CK0+170","CK0+290","CK0+410","CK0+530","SK2+612","SK2+732","SK2+852","SK2+972","SK3+92","SK3+212",
#              "SK3+332","SK3+452","SK3+572","SK3+692","SK3+812","SK3+932","SK4+52","SK4+172","SK4+292","SK4+412",
#              "SK4+532","SK4+652","SK4+772","SK4+892","SK5+12","SK5+132","SK5+252","SK5+372"]
# jingdu2=["112.95070420","112.95193436","112.95311898","112.95433648","112.94957464","112.95077642","112.95201492","112.95322798","112.95445299","112.95562815"
#     ,"112.95686263","112.95808045","112.95921592","112.96026266","112.96123660","112.96213835","112.96304267","112.96395687","112.96492783","112.96597795"
#     ,"112.96710892","112.96829700","112.96952545","112.97088762","112.97213569","112.97337246","112.97458480","112.97581377"]
# weidu2=["28.22327535","28.22344910","28.22364285","28.22384075","28.22318344","28.22335228","28.22352963","28.22372878","28.22392333","28.22396856",
#         "28.22385719","28.22358783","28.22317740","28.22263018","28.22194359","28.22121362","28.22047881","28.21973805","28.21906275","28.21851661",
#         "28.21809786","28.21781409","28.21767910","28.21756521","28.21752043","28.21741584","28.21729077","28.21720480",]

nanxian = ["CK0+530", "CK0+410", "CK0+290", "CK0+170", "SK2+132", "SK2+252", "SK2+372", "SK2+492", "SK2+612", "SK2+732",
           "SK2+852", "SK2+972", "SK3+92", "SK3+212", "SK3+332", "SK3+452", "SK3+572", "SK3+692", "SK3+812", "SK3+932",
           "SK4+52", "SK4+172", "SK4+292", "SK4+412", "SK4+532", "SK4+652", "SK4+772", "SK4+892", "SK5+12", "SK5+132",
           "SK5+252", "SK5+372", "EK0+96", "EK0+216"] # 南入口1：CK0+170 南入口2：SK2+132  南出口1：SK5+372  南出口1：EK0+216

beixian = ["GK0+187", "NK5+10","GK0+307",  "NK2+130", "NK2+250", "NK2+370", "NK2+490", "NK2+610", "NK2+730", "NK2+850",
           "NK3+90", "NK3+210", "NK3+330", "NK3+450", "NK3+570", "NK3+690", "NK3+810", "NK3+930", "NK4+50", "NK4+170",
           "NK4+290", "NK4+410", "NK4+530", "NK4+650", "NK4+770", "NK4+890", "NK5+130", "DK0+074",
           "DK0+314","NK2+970", "DK0+194"]  # 北闸入口：GK0+187  北主入口：NK5+10    北主出口：NK2+970   北闸出口：DK0+194
# merged_list = nanxian + beixian

# nanxian = ["CK0+530","SK2+132","EK0+216"]  # 测试车牌识别问题，出入口有一边没数据都不写入iotdb

# 模拟并发场景，每一个雷达数据发完后往后一个雷达传递参数，车牌不变，调整桩号，设备、时间，速度、车道取随机数；每个雷达随机发送(s-e)次
# path是线路   device是设备名  long_list对应经度列表   lat_list对应纬度列表
def publishNanxian2(path,device,long_list,lat_list,n,s,e):
    # 实例化 MQTTClient
    mqtt_client = MQTTClient()

    all_vehicle_data1 = creatRealData(path, device, len(path))
    # print(all_vehicle_data1)

    for _ in range(n):
        for k in range(random.randint(s,e)):
            # mqtt_client.concurrent_publish('objects_list', all_vehicle_data1)
            print(all_vehicle_data1)
            sleep(1)
            current_time = datetime.now().strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]
            for l in range(len(all_vehicle_data1)):
                all_vehicle_data1[l]['timestamp'] = current_time


        data_length = len(all_vehicle_data1)
        for j in range(data_length - 1):
            current_time = datetime.now().strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]
            all_vehicle_data1[j]['location'] = all_vehicle_data1[j + 1]['location']
            all_vehicle_data1[j]['device_num'] = all_vehicle_data1[j + 1]['device_num']
            all_vehicle_data1[j]['timestamp'] = current_time
            for obj in all_vehicle_data1[j]['objects_list']:
                obj['lane'] = random.randint(1, 3)
                obj['stake_mark'] = path[j + 1]
                obj['longitude'] = long_list[j + 1]
                obj['latitude'] = lat_list[j + 1]
                obj['speed'] = round(random.uniform(0, 100), 2)
        all_vehicle_data1 = creatRealData(path, device, 1) + all_vehicle_data1[:-1]

# 参数分别是线路/设备名/对应经度列表/对应纬度列表/车往后走几个桩位/每次数据在同一个雷达随机开始次数/每次数据在同一个雷达随机结束次数
# publishNanxian2(nanxian2,'south',jingdu2,weidu2,5,2,3)



# 临时测试用
# 实例化 MQTTClient
mqtt_client = MQTTClient()

# 发布多个不同参数的消息(暂时用这个)
for i in range(1):
    # 模拟65个设备的数据
    all_vehicle_data1 = creatData(nanxian, 'xiangyalu', len(nanxian))
    all_vehicle_data2 = creatData(beixian, 'xiangyalu', len(beixian))
    print(all_vehicle_data1)
    print(all_vehicle_data2)
    mqtt_client.publish_multiple_messages("bizdata/objects_list", all_vehicle_data1)
    mqtt_client.publish_multiple_messages("bizdata/objects_list", all_vehicle_data2)
    sleep(30)
    i += 1

